/**
 * 剑指 Offer 04. 二维数组中的查找
 * https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/
 */

/**
 * @param {number[][]} matrix
 * @param {number} target
 * @return {boolean}
 */
function findNumberIn2DArray(matrix, target) {
  let { length: m } = matrix;
  if (!m) {
    return false;
  }
  let { length: n } = matrix[0];
  if (!n) {
    return false;
  }
  m = 0;
  n -= 1;
  while (m < matrix.length && n >= 0) {
    if (matrix[m][n] === target) {
      return true;
    }
    if (matrix[m][n] > target) {
      n -= 1;
    } else {
      m += 1;
    }
  }
  return false;
}

console.log(findNumberIn2DArray([
  [1, 4, 7, 11, 15],
  [2, 5, 8, 12, 19],
  [3, 6, 9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30],
], 5) === true);
console.log(findNumberIn2DArray([
  [1, 4, 7, 11, 15],
  [2, 5, 8, 12, 19],
  [3, 6, 9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30],
], 20) === false);
